(function () {
  function jQuery(selector) {
    return new jQuery.prototype.init(selector);
  }

  jQuery.prototype.init = function(selector) {
    this.length = 0;  // 初始化length 长度
    var dom = null;
    if(selector == null) {
      return this;
    } else if(typeof selector == "object") {
      dom = selector;
    } else if(selector.indexOf('.') !== -1) { // 如果为class选择器
      dom = document.getElementsByClassName(selector.slice(1))
    }else if(selector.indexOf('#') !== -1) { // 如果为id选择器
      dom = document.getElementById(selector.slice(1))
    } else {
      dom = document.querySelectorAll(selector)
    }

    if(dom.length == undefined) {
      this[0] = dom;
      this.length ++;
    } else {
      for(let i = 0; i < dom.length; i ++) {
        this[i] = dom[i];
        this.length ++;
      }
    }

  }

  jQuery.prototype.css = function (config) {
    // 循环操作
    for(let i = 0; i < this.length; i ++) {
      for(let key in config) {
        this[i].style[key]  = config[key];
      }
    }

    return this; //jq 链式调用
  }

  jQuery.prototype.get = function (i) {
      // if(i == null) {
      //   // 类数组转数组
      //   return Array.prototype.slice.call(this,0);
      // } else { // 具体的数字
      //   if(i >= 0) {
      //     return this[0]
      //   } else {
      //     return this[this.length + i];
      //   }
      // }

      return i == null ? ([].slice.call(this,0)) : (i >= 0 ? this[i] : this[i + this.length]);
  }

  jQuery.prototype.eq = function (i) {
    let dom =  i == null ? null : (i >= 0 ? this[i] : this[i + this.length]);

    return  jQuery(dom);
  }


  jQuery.prototype.val = function(val) {
    if(val === undefined) {
      return this[0].value;
    } else {
      this[0].value = val
      return this;
    }
  }

  jQuery.prototype.show = function () {
    for(let i = 0; i < this.length; i ++) {
        this[i].style.display  = "block";
    }

    return this;
  }

  jQuery.prototype.hide = function () {
    for(let i = 0; i < this.length; i ++) {
        this[i].style.display  = "none";
    }

    return this;
  }


  jQuery.prototype.pushStack = function (dom) {
    if(dom.controuctor != jQuery) {
      dom = jQuery(dom);
    }
    dom.prevObject = this
    return dom;
  }

  jQuery.prototype.add = function (selector) {

    let curObj = jQuery(selector);
    let baseObj = this;
    let newObj = jQuery();

    for(let i = 0; i < curObj.length; i ++) {
      newObj[newObj.length ++] = curObj[i]
    }
    for(let i = 0; i < baseObj.length; i ++) {
      newObj[newObj.length ++] = baseObj[i]
    }


    newObj = this.pushStack(newObj);
    return newObj;
  }

  jQuery.prototype.end = function () {
    return this.prevObject;
  }



  //
  jQuery.prototype.init.prototype = jQuery.prototype;  // 原型共享
  window.$ = window.jQuery = jQuery;
})()